<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Services\EasyWeChatServices;
use App\Models\WxPayRecord;
use App\Services\SendCouponServices;
use App\Models\User;
use App\Models\Goods;

class NotifyController extends Controller
{
    public function wx_order_notify(Order $order,SendCouponServices $couponServices,User $user,Goods $goods,EasyWeChatServices $easyWeChatServices){
        // 支付回调

            try{
                // 获取json 数据
                $xml = file_get_contents('php://input');

                $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));

                $param = json_decode($jsonxml, true);//转成数组

                if(!isset($param['return_code'])){
                    Log::notice("回调参数json转数组有误 找不到return_code\r\n");
                    //throw new \Exception('支付失败');0
                    return false;
                }

                if($param['return_code'] == 'SUCCESS' && $param['result_code'] == 'SUCCESS'){
                    // 支付成功
                    $traceNo =$param['out_trade_no'];
                    Log::info("接收到回调,微信返回{$traceNo} \r\n");
                    $orderObj = $order
                        ->where('order_number','=',$traceNo)
                        //->where('order_status',1)
                        ->first();


                    // 验证是否存在该订单
                    if(empty($orderObj)){
                        Log::info("订单异常,找不到订单号为{$traceNo}的订单 \r\n");
                        Log::info("订单异常,找不到订单号微信返回{$traceNo} \r\n");
                        throw new \Exception('订单异常');
                        return false;
                    }

                    $wx_record = WxPayRecord::where('out_trade_no',$traceNo)
                        ->where('status',3)
                        ->first();

                    $wx_openid = $user
                        ->where('id',$orderObj->user_id)
                        ->value('wx_openid');

                    if($orderObj->order_status != 1){
                        Log::info("订单异常,订单号为{$traceNo}状态不能支付 \r\n");
                        Log::info('订单异常,订单号为{$traceNo}状态不能支付 \r\n'.json_encode($orderObj));
                        //throw new \Exception('订单异常');
                        return false;
                    }

                    //查询银行
                    $pay_app = EasyWeChatServices::pay_app();
                    $chaeck_app = $pay_app->order->queryByOutTradeNumber($traceNo);
                    Log::info("记录查询-订单号为{$traceNo}的订单 \r\n".json_encode($chaeck_app));
                    if($chaeck_app["return_code"] != 'SUCCESS'){
                        Log::info("订单异常,查询不到微信服务器订单信息 \r\n");
                        //throw new \Exception('订单异常');
                        return false;
                    }

                    // 验证订单是否为待付款状态
                    if ($chaeck_app['bank_type'] != 'ABC_CREDIT'){
                        Log::info("开始退款-订单号为{$traceNo}的订单不是ABC_CREDIT-银行卡 \r\n");
                        $refundes_result = $easyWeChatServices->RefundedNotify($orderObj->order_number,order_number(),$orderObj->order_price * 100,$orderObj->order_price * 100);
                        //Log::info('退款数据'.json_encode($refundes_result));
                        if($refundes_result){
                            Log::info("退款成功-订单号为{$traceNo}的订单不是ABC_CREDIT-银行卡 \r\n");
                            return true;
                        }else{
                            Log::info("退款失败-订单号为{$traceNo}的订单不是ABC_CREDIT-银行卡 \r\n");
                            return false;
                        }
                    }
                    //发劵
                    $send_sesult = $couponServices->send_coupon($orderObj->stock_id,$wx_openid);
                    $wx_record->json = json_encode($send_sesult);
                    if($send_sesult['return_code'] == 'SUCCESS' && $send_sesult['result_code']== 'SUCCESS'){
                        //更改发劵状态
                        $orderObj->is_grant = 1;
                        $orderObj->order_status = 2;
                        //$orderObj->sold_total = $orderObj->sold_total + 1;
                        $orderObj->coupon_id = $send_sesult['coupon_id'];
                        $orderObj->save();

                        $goods = $goods->where('id',$orderObj->goods_id)->first();

                        $goods->increment('sold_total');
                        $wx_record->status = 1;
                        $wx_record->save();
                        Log::info("发劵成功 \r\n");
                        Log::info('發劵數據'.json_encode($send_sesult));
                        return true;
                    }else{
                        $wx_record->save();
                        Log::info("发劵失败 \r\n");
                        $msg = $send_sesult['err_code_des'];
                        $refundes_result = $easyWeChatServices->RefundedNotify($orderObj->order_number,order_number(),
                            $orderObj->order_price * 100,$orderObj->order_price * 100,$msg);
                        if($refundes_result){
                            Log::info("退款成功-订单号为{$traceNo}的订单發劵失敗 \r\n");
                            return true;
                        }else{
                            Log::info("退款失败-订单号为{$traceNo}的订单發劵失敗 \r\n");
                            return false;
                        }
                        return false;
                    }
                }else{
                    Log::info("接收回调参数有误 \r\n");
                    //throw new \Exception('支付失败');
                    return false;
                }
                Log::info('没有返回发劵'.json_encode($send_sesult));
            }catch (\Exception $e){

                Log::info('代码错误'.$e -> getMessage());
                return false;
            }

    }


}
